﻿<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Form.ascx.cs" Inherits="AttendanceWebForm_LeaveData_Form" %>
<%@ Import Namespace="System.Data" %>
<script runat="server">
    protected void ddlLeaveType_DataBinding(object sender, EventArgs e)
    {
        (sender as ListControl).DataValueField = "Value";
        (sender as ListControl).DataTextField = "Text";
        (sender as ListControl).DataSource = CodeManager.Current.GetData("LeaveData", "LeaveType");

        if (fv.CurrentMode == FormViewMode.Edit)
        {
            (sender as ListControl).Text = Eval("LeaveType", "");
        }
    }

    protected void vadLeaveDate_OnValidate(object sender, ServerValidateEventArgs e)
    {
        DateTime startDate, endDate;
        List<string> errMessage = new List<string>();
        
        if (DateTime.TryParse((fv.FindControl("txtLeaveStartDate") as ITextControl).Text, out startDate) == false)
        {
            errMessage.Add(this.GetLocalResourceObject("vadHour_InvalidStartDate").ToString());
        }

        startDate += (fv.FindControl("txtLeaveStartTime") as IValueControl<TimeSpan>).Value;

        if (DateTime.TryParse((fv.FindControl("txtLeaveEndDate") as ITextControl).Text, out endDate) == false)
        {
            errMessage.Add(this.GetLocalResourceObject("vadHour_InvalidEndate").ToString());
        }

        endDate += (fv.FindControl("txtLeaveEndTime") as IValueControl<TimeSpan>).Value;

        if (errMessage.Count > 0) goto setErrorMessage;

        if (startDate.Year != endDate.Year)
        {
            errMessage.Add(this.GetLocalResourceObject("vadHour_CrossYear").ToString());
        }

        if (errMessage.Count > 0) goto setErrorMessage;

        var db = new DB("Attendance");
        
        // 判斷是否不在上班時間
        //// 取得上班時間
        var workGroup = db.ExecuteRow("SELECT * FROM WorkGroup wg WHERE WorkGroupID = @WorkGroupID"
            , new DBParameter("WorkGroupID", EmpManager.Current["WorkGroupID"]));

        var workBreakData = db.Execute("SELECT * FROM WorkBreak wg WHERE WorkGroupID = @WorkGroupID"
            , new DBParameter("WorkGroupID", EmpManager.Current["WorkGroupID"]));

        if (InWorkHour((fv.FindControl("txtLeaveStartTime") as IValueControl<TimeSpan>).Value, workGroup) == false
            || InWorkHour((fv.FindControl("txtLeaveEndTime") as IValueControl<TimeSpan>).Value, workGroup) == false
            || endDate <= startDate
            || InBreakTime((fv.FindControl("txtLeaveStartTime") as IValueControl<TimeSpan>).Value, workBreakData) == true
            || InBreakTime((fv.FindControl("txtLeaveEndTime") as IValueControl<TimeSpan>).Value, workBreakData) == true)
        {
            errMessage.Add(this.GetLocalResourceObject("vadHour_HolidayConflict").ToString());
        }

        if (errMessage.Count > 0) goto setErrorMessage;

        var holidays = db.ExecuteListScalar<DateTime>(@"SELECT h.Date FROM Holiday h 
                INNER JOIN HolidayGroup hg ON h.HolidayGroupID = hg.HolidayGroupID
                INNER JOIN WorkGroup wg ON hg.HolidayGroupID = wg.WorkGroupID
                WHERE wg.WorkGroupID = @WorkGroupID"
            , new DBParameter("WorkGroupID", EmpManager.Current["WorkGroupID"]));
                
        // 計算時數        
        //// 目前可用時數
        float availableHours = LeaveManager.Current.GetAvailableLeaveHours((fv.FindControl("txtEmpID") as ITextControl).Text);

        // 計算本次請假時數
        DateTime d = startDate;
        this.LeaveHours = 0;

        while (d < endDate)
        {
            var t = TimeSpan.Parse(string.Format("{0}:{1}", d.Hour, d.Minute));
            
            // 時數需在上班時間內且不為上班休息時間, 且不為例假日
            if (InWorkHour(t += new TimeSpan(1), workGroup) == true && InBreakTime(t += new TimeSpan(1), workBreakData) == false
                    && holidays.Contains(d.Date) == false)
            {
                this.LeaveHours += 0.5F;
            }
            
            d = d.AddMinutes(30);
        }

        if (LeaveHours > availableHours)
        {
            errMessage.Add(string.Format(GetLocalResourceObject("vadHour_OverQuota").ToString()
                , LeaveHours, availableHours));
        }

        if (errMessage.Count > 0) goto setErrorMessage;
        
setErrorMessage:        
        if (errMessage.Count > 0)
        {
            e.IsValid = false;
            (sender as IValidator).ErrorMessage = MyObj.JoinFormat(" ", "{0}", errMessage);
        }
    }

    protected bool InBreakTime(TimeSpan d, DataTable workBreakData)
    {
        foreach (DataRow dr in workBreakData.Rows)
        {
            if ((TimeSpan)dr["WorkBreakStartTime"] <= d && d < (TimeSpan)dr["WorkBreakEndTime"])
            {
                return true;
            }
        }       

        return false;
    }

    protected bool InWorkHour(TimeSpan d, DataRow workGroup)
    {
        if ((TimeSpan)workGroup["WorkStartTime"] <= d && d <= (TimeSpan)workGroup["WorkEndTime"])
        {
            return true;
        }        
        
        return false;
    }    
    
</script>
<My:MyFormView ID="fv" runat="server" OnItemCommand="fv_ItemCommand" OnDataBound="fv_DataBound" OnSaving="fv_Saving" OnSaved="fv_Saved">
    <EditItemTemplate>
        <table>
            <tr>
                <td class="label">
                    <asp:Localize ID="Localize1" runat="server" Text="<%$Resources: LeaveData, EmpID %>"></asp:Localize>
                </td>
                <td class="text">
                    <asp:TextBox ID="txtEmpID" runat="server" Text='<%# Eval("EmpID") %>'></asp:TextBox>
                    <My:InputTip ID="tipEmpID" runat="server" Must="true" Text="<%$Resources:tipEmpID.Text   %>" />
                </td>
            </tr>
            <tr>
                <td class="label">
                    <asp:Localize ID="Localize9" runat="server" Text="<%$Resources: LeaveData, LeaveType %>"></asp:Localize>
                </td>
                <td class="text">
                    <My:MyDropDownList ID="ddlLeaveType" runat="server" OnDataBinding="ddlLeaveType_DataBinding"
                        EmptyText="<%$Resources: Form, ddl.EmptyText %>">
                    </My:MyDropDownList>
                    <My:InputTip ID="InputTip3" runat="server" Must="true" />
                </td>
            </tr>
            <tr>
                <td class="label">
                    <asp:Localize ID="Localize2" runat="server" Text="<%$Resources: LeaveData, LeaveStartDate %>"></asp:Localize>
                </td>
                <td class="text">
                    <My:DateInput ID="txtLeaveStartDate" runat="server" />
                    <My:LeaveHourInput ID="txtLeaveStartTime" runat="server" />
                    <My:InputTip ID="InputTip1" runat="server" Must="true" Text="<%$Resources: tipLeaveTime.Text %>" />
                </td>
            </tr>
            <tr>
                <td class="label">
                    <asp:Localize ID="Localize3" runat="server" Text="<%$Resources: LeaveData, LeaveEndDate %>"></asp:Localize>
                </td>
                <td class="text">
                    <My:DateInput ID="txtLeaveEndDate" runat="server" />
                    <My:LeaveHourInput ID="txtLeaveEndTime" runat="server" />
                    <My:InputTip ID="InputTip2" runat="server" Must="true" Text="<%$Resources: tipLeaveTime.Text %>" />
                </td>
            </tr>
        </table>
        <p>
        </p>
        <asp:Button ID="btnSave" runat="server" CommandName="MySave" Text="<%$Resources: Form, btnSend %>" ValidationGroup="Form" />
        <asp:Button ID="btnCancel" runat="server" CommandName="MyCancel" Text="<%$Resources: Form, btnCancel %>" />
        <ajax:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server" TargetControlID="btnSave"
            ConfirmText="<%$Resources: Form, cbSend %>">
        </ajax:ConfirmButtonExtender>

        <%--假別檢核--%>
        <asp:RequiredFieldValidator ID="vadLeaveType" runat="server" ControlToValidate="ddlLeaveType" Text="<%$Resources: vadLeaveType.Text %>" EnableClientScript="false" ValidationGroup="Form"></asp:RequiredFieldValidator>
        <%--請假日期檢核--%>
        <asp:CustomValidator ID="vadLeaveDate" runat="server" OnServerValidate="vadLeaveDate_OnValidate" ValidationGroup="Form"></asp:CustomValidator>
    </EditItemTemplate>
</My:MyFormView>
